package com.shengzai.rdd

import org.apache.spark.rdd.RDD
import org.apache.spark.{SparkConf, SparkContext}

object Demo13Join {
  def main(args: Array[String]): Unit = {

    val conf = new SparkConf()
    conf.setMaster("local")
    conf.setAppName("join")

    val sc = new SparkContext(conf)

    val idAndNameRDD: RDD[(String, String)] = sc.parallelize(
      List(
        ("001", "张三"),
        ("002", "李四"),
        ("003", "赵六"),
        ("004", "王五")
      )
    )
    val idAndAgeRDD: RDD[(String, Int)] = sc.parallelize(
      List(
        ("001", 23),
        ("002", 24),
        ("003", 26),
        ("005", 25)
      )
    )
    /**
     * join 内关联，只关联保存成功的数据
     */
    val joinRDD: RDD[(String, (String, Int))] = idAndNameRDD.join(idAndAgeRDD)
    joinRDD.foreach(println)

    /**
     * leftJoin 左关联，没有数据用None补齐
     */
    val leftJoinRDD: RDD[(String, (String, Option[Int]))] = idAndNameRDD.leftOuterJoin(idAndAgeRDD)
    val leftJoinResRDD: RDD[(String, String, Int)] = leftJoinRDD.map {
      case (id: String, (name: String, Some(age))) =>
        (id, name, age)
      case (id: String, (name: String, None)) =>
        (id, name, 0)
    }
    leftJoinResRDD.foreach(println)
    /**
     * fullJoinRDD保留两个表所有的值
     */
    val fullJoinRDD: RDD[(String, (Option[String], Option[Int]))] = idAndNameRDD.fullOuterJoin(idAndAgeRDD)
    val resFullJoin: RDD[String] = fullJoinRDD.map {
      case (id: String, (Some(name), Some(age))) =>
        s"$id\t$name\t$age"
      case (id: String, (None, Some(age))) =>
        s"$id\t未知\t$age"
      case (id: String, (Some(name), None)) =>
        s"$id\t$name\t0"
    }
    resFullJoin.foreach(println)

  }

}
